#include <QTabWidget>
#include <QVBoxLayout>
#include <QPluginLoader>
#include <QDir>
#include <QTabBar>
#include <QDebug>
#include <QySciEdit>
#include <QyFileSystemBrowser>

#include "QySourceNavigator.h"
#include "QySourceNavigatorPluginInterface.h"

/**************************************************************************************************/

QySourceNavigatorPluginInterface::~QySourceNavigatorPluginInterface() {

	// nothing

}

QySciEdit * QySourceNavigatorPluginInterface::currentEdit() const {

	return p_edit;
}

void QySourceNavigatorPluginInterface::setCurrentEdit( QySciEdit * edit ) {

	p_edit = edit;

	currentEditChanged(p_edit);

}

void QySourceNavigatorPluginInterface::currentEditChanged( QySciEdit * ) {

	// nothing

}

/**************************************************************************************************/

QySourceNavigator::QySourceNavigator( QWidget * parent ) : QWidget(parent) {

	QVBoxLayout * layout = new QVBoxLayout(this);
	p_tabWidget = new QTabWidget(this);
	QyFileSystemBrowser * fsBrowser = new QyFileSystemBrowser(this);

	layout->addWidget(p_tabWidget);
	p_tabWidget->setTabPosition(QTabWidget::East);
	p_tabWidget->addTab( fsBrowser, tr("File System") );

	connect( fsBrowser, SIGNAL( activated(const QString &) ),
		fsBrowser, SLOT( setPath(const QString &) ) );
	connect( fsBrowser, SIGNAL( activated(const QString &) ),
		this, SIGNAL( fileOpend(const QString &) ) );

}

void QySourceNavigator::loadPluginsFrom( const QString & dirPath ) {

	QStringList files( QDir(dirPath).entryList(QDir::Files) );

    foreach ( QString fileName, files ) {

        QPluginLoader loader( dirPath + "/" + fileName );
		QObject * plugin = loader.instance();

        if (  QySourceNavigatorPluginInterface * snPlugin =
			qobject_cast<QySourceNavigatorPluginInterface *>(plugin) )
		{

			snPlugins.append(snPlugin);
			p_tabWidget->addTab( snPlugin->widget(), snPlugin->displayName() );

        }

    }

}

void QySourceNavigator::setCurrentEdit( QySciEdit * edit ) {

	foreach ( QySourceNavigatorPluginInterface * snPlugin, snPlugins )
		snPlugin->setCurrentEdit(edit);

}

void QySourceNavigator::focusInEvent( QFocusEvent * event ) {

	QWidget::focusInEvent(event);

	if ( QWidget * page = p_tabWidget->currentWidget() )
		page->setFocus();

}
